<?php

namespace App\Http\Dao;

abstract class BaseDao
{
    public function getList(string $where = '', string $limit = '', string $order = '', string $fields = '*', string $group = '')
    {
        $query = $this->getModel()::select($fields);

        if ($where) $query->whereRaw($where);
        if ($group) $query->groupBy($group);
        if ($order) $query->orderByRaw($order);
        if ($limit) $query->limit($limit);

        return $query->get();
    }

    abstract protected function getModel(): string;

    public function getOne($where)
    {
        return $this->getModel()::query()->where($where)->first();
    }


    // 新增
    public function add($data)
    {
        $data['created_at'] = $data['updated_at'] = strtotime(date('Y-m-d H:i:s'));
        // 添加并返回主键
        return $this->getModel()::query()->insertGetId($data);
    }

    public function editOne($data, $where = [])
    {
        $data['updated_at'] = strtotime(date('Y-m-d H:i:s'));
        if (!empty($where)) {
            return $this->getModel()::query()->where($where)->update($data);
        } else {
            return $this->getModel()::query()->where('id', $data['id'])->update($data);
        }
    }

    public function deleteOne($id, $softDelete = true)
    {
        if ($softDelete) {
            return $this->getModel()::query()->where('id', $id)->update(['deleted_at' => strtotime(date('Y-m-d H:i:s'))]);
        } else {
            return $this->getModel()::query()->where('id', $id)->delete();
        }
    }
}
